<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="简介greendao是一个开源的Android开发ORM使SQLite数据库，可以减轻和节省开发时间的同时处理低级别的数据库需求。SQLite是一个很好的嵌入式关系数据库，不过写SQL解析查询结果是相当繁琐和耗时的，greendao可以让你利用java对象来映射到数据库表便捷的使用Java面相对象的API来处理增、删、改、查的操作。 特点 性能大（貌似是Android最快的ORM） 易用性高 内存">
<meta name="keywords" content="Android">
<meta property="og:type" content="article">
<meta property="og:title" content="你必须了解的ORM框架GreenDao">
<meta property="og:url" content="http://soaic.github.io/2016/12/13/2016-12-13-greendao/index.html">
<meta property="og:site_name" content="Soaic&#39;s Blog">
<meta property="og:description" content="简介greendao是一个开源的Android开发ORM使SQLite数据库，可以减轻和节省开发时间的同时处理低级别的数据库需求。SQLite是一个很好的嵌入式关系数据库，不过写SQL解析查询结果是相当繁琐和耗时的，greendao可以让你利用java对象来映射到数据库表便捷的使用Java面相对象的API来处理增、删、改、查的操作。 特点 性能大（貌似是Android最快的ORM） 易用性高 内存">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-08-19T03:45:40.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="你必须了解的ORM框架GreenDao">
<meta name="twitter:description" content="简介greendao是一个开源的Android开发ORM使SQLite数据库，可以减轻和节省开发时间的同时处理低级别的数据库需求。SQLite是一个很好的嵌入式关系数据库，不过写SQL解析查询结果是相当繁琐和耗时的，greendao可以让你利用java对象来映射到数据库表便捷的使用Java面相对象的API来处理增、删、改、查的操作。 特点 性能大（貌似是Android最快的ORM） 易用性高 内存">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://soaic.github.io/2016/12/13/2016-12-13-greendao/"/>





  <title>你必须了解的ORM框架GreenDao | Soaic's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Soaic's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Soaic</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-music">
          <a href="/music/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-music"></i> <br />
            
            音乐
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://soaic.github.io/2016/12/13/2016-12-13-greendao/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Soaic">
      <meta itemprop="description" content="Welcome!">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Soaic's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">你必须了解的ORM框架GreenDao</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-12-13T16:46:00+08:00">
                2016-12-13
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android框架/" itemprop="url" rel="index">
                    <span itemprop="name">Android框架</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2016/12/13/2016-12-13-greendao/" class="leancloud_visitors" data-flag-title="你必须了解的ORM框架GreenDao">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h3><p>greendao是一个开源的Android开发ORM使SQLite数据库，可以减轻和节省开发时间的同时处理低级别的数据库需求。SQLite是一个很好的嵌入式关系数据库，不过写SQL解析查询结果是相当繁琐和耗时的，greendao可以让你利用java对象来映射到数据库表便捷的使用Java面相对象的API来处理增、删、改、查的操作。</p>
<h3 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h3><ol>
<li>性能大（貌似是Android最快的ORM）</li>
<li>易用性高</li>
<li>内存消耗极小</li>
<li>精简的库（小于100KB）</li>
<li>安全性高（支持SQLCipher来保持用户的数据安全）</li>
<li>支持RxJava</li>
</ol>
<a id="more"></a>
<h3 id="资料"><a href="#资料" class="headerlink" title="资料"></a>资料</h3><ol>
<li>官网：<a href="http://greenrobot.org/greendao/" target="_blank" rel="external">http://greenrobot.org/greendao/</a></li>
<li>github：<a href="https://github.com/greenrobot/greenDAO" target="_blank" rel="external">https://github.com/greenrobot/greenDAO</a></li>
</ol>
<h3 id="配置环境"><a href="#配置环境" class="headerlink" title="配置环境"></a>配置环境</h3><p>在build.gradle中配置</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">apply plugin: <span class="string">'com.android.library'</span>  </div><div class="line"><span class="comment">//应用greendao插件</span></div><div class="line">apply plugin: <span class="string">'org.greenrobot.greendao'</span>        </div><div class="line">android &#123;</div><div class="line">    compileSdkVersion <span class="number">25</span></div><div class="line">    buildToolsVersion <span class="string">"25.0.0"</span></div><div class="line">    defaultConfig &#123;</div><div class="line">        minSdkVersion <span class="number">15</span></div><div class="line">        targetSdkVersion <span class="number">25</span></div><div class="line">        versionCode <span class="number">1</span></div><div class="line">        versionName <span class="string">"1.0"</span></div><div class="line">    &#125;</div><div class="line">    buildTypes &#123;</div><div class="line">        release &#123;</div><div class="line">            minifyEnabled <span class="literal">false</span></div><div class="line">            proguardFiles getDefaultProguardFile(<span class="string">'proguard-android.txt'</span>), <span class="string">'proguard-rules.pro'</span></div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">//greendao相关配置</span></div><div class="line">greendao &#123;</div><div class="line">    schemaVersion <span class="number">1</span>                 <span class="comment">//数据库版本号</span></div><div class="line">    daoPackage <span class="string">'com.greendao.dao'</span>    <span class="comment">//greendao自动生成的dao文件包名</span></div><div class="line">    targetGenDir <span class="string">'src/main/java'</span>    <span class="comment">//greendao自动生成的目标文件夹</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">//从maven中下载greendao插件</span></div><div class="line">buildscript &#123;</div><div class="line">    repositories &#123;</div><div class="line">        mavenCentral()</div><div class="line">    &#125;</div><div class="line">    dependencies &#123;</div><div class="line">        classpath <span class="string">'org.greenrobot:greendao-gradle-plugin:3.2.0'</span></div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">//添加greendao需要的编译环境</span></div><div class="line">dependencies &#123;</div><div class="line">    compile fileTree(dir: <span class="string">'libs'</span>, <span class="attr">include</span>: [<span class="string">'*.jar'</span>])</div><div class="line">    compile <span class="string">'com.android.support:appcompat-v7:25.0.0'</span></div><div class="line">    compile <span class="string">'com.android.support:recyclerview-v7:25.0.0'</span></div><div class="line">    compile <span class="string">'org.greenrobot:greendao:3.2.0'</span></div><div class="line">    compile <span class="string">'org.greenrobot:greendao-generator:3.2.0'</span></div><div class="line">    compile <span class="string">'io.reactivex:rxandroid:1.2.1'</span></div><div class="line">    compile <span class="string">'io.reactivex:rxjava:1.1.6'</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>然后点击Sync Project with Gradle Files按钮下载编译环境，等待下载完成，环境配置就OK了。</p>
<h3 id="开始"><a href="#开始" class="headerlink" title="开始"></a>开始</h3><p>GreenDao3.0以后开始用注解配置数据表，使用起来非常快捷方便，下面代码简单的配置了User表，表里面有id和name两个字段</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="meta">@Entity</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span></span>&#123;</div><div class="line">    <span class="meta">@Id</span></div><div class="line">    <span class="keyword">private</span> Long id;</div><div class="line"></div><div class="line">    <span class="meta">@NotNull</span></div><div class="line">    <span class="keyword">private</span> String name;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>然后用Build里面的Make Project或Make Module来自动生成相关DAO类和get set方法，完成之后，在我们定义好的com.greendao.dao包下也会多出DaoMaster、DaoSession、UserDao三个类，代码这里就不贴出来了，User实体会生成如下：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="meta">@Entity</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span></span>&#123;</div><div class="line"></div><div class="line">    <span class="meta">@Id</span></div><div class="line">    <span class="keyword">private</span> Long id;</div><div class="line">    </div><div class="line">    <span class="meta">@NotNull</span></div><div class="line">    <span class="keyword">private</span> String name;</div><div class="line"></div><div class="line">    <span class="meta">@Generated</span>(hash = <span class="number">1709734220</span>)</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">User</span><span class="params">(Long id, @NotNull String name)</span> </span>&#123;</div><div class="line">        <span class="keyword">this</span>.id = id;</div><div class="line">        <span class="keyword">this</span>.name = name;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Generated</span>(hash = <span class="number">586692638</span>)</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">User</span><span class="params">()</span> </span>&#123;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> Long <span class="title">getId</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.id;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setId</span><span class="params">(Long id)</span> </span>&#123;</div><div class="line">        <span class="keyword">this</span>.id = id;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.name;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">        <span class="keyword">this</span>.name = name;</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><b>数据表注解@Entity的详细配置</b></p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="meta">@Entity</span>(</div><div class="line">    <span class="comment">// 目前还不是很清楚这个字段的功能和意义</span></div><div class="line">    schema = <span class="string">"myschema"</span>,</div><div class="line">    </div><div class="line">    <span class="comment">// 是否需要更新、删除属性和刷新方法，默认为true</span></div><div class="line">    active = <span class="keyword">true</span>,</div><div class="line">    </div><div class="line">    <span class="comment">//指定数据库中的表的名称。默认是实体类的名称。</span></div><div class="line">    nameInDb = <span class="string">"AWESOME_USERS"</span>,</div><div class="line">    </div><div class="line">    <span class="comment">// 定义跨越多个列的索引。</span></div><div class="line">    indexes = &#123;</div><div class="line">            <span class="meta">@Index</span>(value = <span class="string">"name DESC"</span>, unique = <span class="keyword">true</span>)</div><div class="line">    &#125;,</div><div class="line">    </div><div class="line">    <span class="comment">// 默认为true,创建数据表，如果有多个实体映射到一个表或表创建在greenDao之外，则设置false</span></div><div class="line">    createInDb = <span class="keyword">false</span>,</div><div class="line"></div><div class="line">    <span class="comment">// 是否生成一个所有属性的构造函数，无参构造函数默认生成</span></div><div class="line">    generateConstructors = <span class="keyword">true</span>,</div><div class="line"></div><div class="line">    <span class="comment">// 是否自动生成get和set方法</span></div><div class="line">    generateGettersSetters = <span class="keyword">true</span></div><div class="line">)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</div><div class="line">  ...</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>注意：如果定义了 schema=”myschema”，会报如下错误，具体解决方法暂时还没找到，有知道的小伙伴可以留言告知一下哦</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">* What went wrong:</div><div class="line">Execution failed <span class="keyword">for</span> task <span class="string">':greendaolibrary:greendao'</span>.</div><div class="line">&gt; Undefined schema \<span class="string">"myschema\" (referenced in entities: User).</span></div><div class="line"><span class="string">Please, define non-default schemas explicitly inside build.gradle</span></div></pre></td></tr></table></figure>
<p><b>各个字段的详细注解</b></p>
<p><code>@Id</code> 主键ID注解，属性一般long或Long来定义，如果要设该字段为自增属性，那么可以定义为<code>@Id(autoincrement = true)</code></p>
<p><code>@Property</code> 字段名定义注解，<code>@Property(nameInDb = &quot;USER_NAME&quot;)</code>，默认是驼峰法代替下划线，所有字母大写，如 customName 变成 CUSTOM_NAME</p>
<p><code>@NotNull</code> 字段不能为空注解</p>
<p><code>@Transient</code> 字段不添加到数据表注解</p>
<p><code>@Index</code> 字段定义为索引注解，<code>@Index(unique = true)</code>索引添加唯一约束，<code>@Index(name = &quot;indexName&quot;)</code>定义索引名</p>
<p><code>@Unique</code> 字段定义唯一约束注解，并会创建索引</p>
<h3 id="封装"><a href="#封装" class="headerlink" title="封装"></a>封装</h3><p>定义<code>DbCore.java</code>类来获取全局唯一的<code>DaoSession</code>对象，代码如下：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DbCore</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String DEFAULT_DB_NAME = <span class="string">"green_dao.db"</span>;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> DaoMaster daoMaster;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> DaoSession daoSession;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Context mContext;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> String DB_NAME;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">(Context context)</span> </span>&#123;</div><div class="line">        init(context, DEFAULT_DB_NAME);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">(Context context,String dbName)</span> </span>&#123;</div><div class="line">        <span class="keyword">if</span> (context == <span class="keyword">null</span>) &#123;</div><div class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"context can't be null"</span>);</div><div class="line">        &#125;</div><div class="line">        mContext = context.getApplicationContext();</div><div class="line">        DB_NAME = dbName;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> DaoMaster <span class="title">getDaoMaster</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">if</span> (daoMaster == <span class="keyword">null</span>) &#123;</div><div class="line">            OnlineOpenHelper helper = <span class="keyword">new</span> OnlineOpenHelper(mContext, DB_NAME, <span class="keyword">null</span>);</div><div class="line">            daoMaster = <span class="keyword">new</span> DaoMaster(helper.getWritableDatabase());</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> daoMaster;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> DaoSession <span class="title">getDaoSession</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">if</span> (daoSession == <span class="keyword">null</span>) &#123;</div><div class="line">            <span class="keyword">if</span> (daoMaster == <span class="keyword">null</span>) &#123;</div><div class="line">                daoMaster = getDaoMaster();</div><div class="line">            &#125;</div><div class="line">            daoSession = daoMaster.newSession();</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> daoSession;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">enableQueryBuilderLog</span><span class="params">()</span></span>&#123;</div><div class="line">        QueryBuilder.LOG_SQL = <span class="keyword">true</span>;</div><div class="line">        QueryBuilder.LOG_VALUES = <span class="keyword">true</span>;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>OnlineOpenHelper升级帮助类</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">OnlineOpenHelper</span> <span class="keyword">extends</span> <span class="title">DaoMaster</span>.<span class="title">OpenHelper</span></span>&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">OnlineOpenHelper</span><span class="params">(Context context,String name)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(context, name);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">OnlineOpenHelper</span><span class="params">(Context context,String name,SQLiteDatabase.CursorFactory factory)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(context, name, factory);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onUpgrade</span><span class="params">(Database db,<span class="keyword">int</span> oldVersion,<span class="keyword">int</span> newVersion)</span> </span>&#123;</div><div class="line">        Log.i(<span class="string">"greenDAO"</span>, <span class="string">"Upgrading schema from version "</span> + oldVersion + <span class="string">" to "</span> + newVersion );</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>需在<code>在application</code>中初始化</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line">DbCore.init(<span class="keyword">this</span>);                 <span class="comment">//初始化GreenDao</span></div><div class="line">DbCore.enableQueryBuilderLog();    <span class="comment">//打印sql语句日志</span></div></pre></td></tr></table></figure>
<p>封装所有的增删改查、获取Dao、获取RxDao、获取QueryBuilder等方法 到<code>BaseService.java</code>中</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BaseService</span>&lt;<span class="title">T</span>, <span class="title">K</span>&gt;</span>&#123;</div><div class="line">    <span class="keyword">private</span> AbstractDao&lt;T, K&gt; mDao;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BaseService</span><span class="params">(AbstractDao dao)</span> </span>&#123;</div><div class="line">        mDao = dao;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">save</span><span class="params">(T item)</span> </span>&#123;</div><div class="line">        mDao.insert(item);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">save</span><span class="params">(T... items)</span> </span>&#123;</div><div class="line">        mDao.insertInTx(items);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">save</span><span class="params">(List&lt;T&gt; items)</span> </span>&#123;</div><div class="line">        mDao.insertInTx(items);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">saveOrUpdate</span><span class="params">(T item)</span> </span>&#123;</div><div class="line">        mDao.insertOrReplace(item);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">saveOrUpdate</span><span class="params">(T... items)</span> </span>&#123;</div><div class="line">        mDao.insertOrReplaceInTx(items);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">saveOrUpdate</span><span class="params">(List&lt;T&gt; items)</span> </span>&#123;</div><div class="line">        mDao.insertOrReplaceInTx(items);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">deleteByKey</span><span class="params">(K key)</span> </span>&#123;</div><div class="line">        mDao.deleteByKey(key);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">delete</span><span class="params">(T item)</span> </span>&#123;</div><div class="line">        mDao.delete(item);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">delete</span><span class="params">(T... items)</span> </span>&#123;</div><div class="line">        mDao.deleteInTx(items);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">delete</span><span class="params">(List&lt;T&gt; items)</span> </span>&#123;</div><div class="line">        mDao.deleteInTx(items);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">deleteAll</span><span class="params">()</span> </span>&#123;</div><div class="line">        mDao.deleteAll();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">update</span><span class="params">(T item)</span> </span>&#123;</div><div class="line">        mDao.update(item);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">update</span><span class="params">(T... items)</span> </span>&#123;</div><div class="line">        mDao.updateInTx(items);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">update</span><span class="params">(List&lt;T&gt; items)</span> </span>&#123;</div><div class="line">        mDao.updateInTx(items);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span>  T <span class="title">query</span><span class="params">(K key)</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span>  mDao.load(key);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> List&lt;T&gt; <span class="title">queryAll</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> mDao.loadAll();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> List&lt;T&gt; <span class="title">query</span><span class="params">(String where,String... params)</span> </span>&#123;</div><div class="line"></div><div class="line">        <span class="keyword">return</span> mDao.queryRaw(where, params);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> QueryBuilder&lt;T&gt; <span class="title">queryBuilder</span><span class="params">()</span> </span>&#123;</div><div class="line"></div><div class="line">        <span class="keyword">return</span> mDao.queryBuilder();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">count</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> mDao.count();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">refresh</span><span class="params">(T item)</span> </span>&#123;</div><div class="line">        mDao.refresh(item);</div><div class="line"></div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">detach</span><span class="params">(T item)</span> </span>&#123;</div><div class="line">        mDao.detach(item);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> AbstractDao <span class="title">getDao</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="keyword">return</span> mDao;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> RxDao&lt;T,K&gt; <span class="title">getRxDao</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="keyword">return</span>  mDao.rx();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> QueryBuilder&lt;T&gt; <span class="title">getQueryBuilder</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="keyword">return</span>  mDao.queryBuilder();</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>封装<code>User</code>表的所有操作到<code>UserService.java</code>类中，如后面有多个表，则只需简单继承<code>BaseService</code>如下即可，后面，所有相关User操作只需通过<code>UserService.getInstance()</code>来实现所有操作</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserService</span> <span class="keyword">extends</span> <span class="title">BaseService</span>&lt;<span class="title">User</span>,<span class="title">Long</span>&gt;</span>&#123;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">UserService</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(DbCore.getDaoSession().getUserDao());</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> UserService <span class="title">getInstance</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="keyword">return</span> SingleLoader.INSTANCE;</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">SingleLoader</span></span>&#123;</div><div class="line">        <span class="keyword">final</span> <span class="keyword">static</span> UserService INSTANCE = <span class="keyword">new</span> UserService();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h3><p><b>增</b></p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">insert</span><span class="params">()</span></span>&#123;</div><div class="line">    String userName = user_name.getText().toString();</div><div class="line">    <span class="keyword">if</span>(TextUtils.isEmpty(userName))&#123;</div><div class="line">       <span class="keyword">return</span>; </div><div class="line">    &#125;</div><div class="line">    User user = <span class="keyword">new</span> User(<span class="keyword">null</span>,userName);</div><div class="line"></div><div class="line">    <span class="comment">//UserService.getInstance().save(user);                 //方式一</span></div><div class="line">    <span class="comment">//UserService.getInstance().getDao().save(user);        //方式二</span></div><div class="line">    UserService.getInstance().getRxDao().insert(user)        <span class="comment">//方式三 Rx模式</span></div><div class="line">            .observeOn(AndroidSchedulers.mainThread())</div><div class="line">            .subscribe(<span class="keyword">new</span> Action1&lt;User&gt;() &#123;</div><div class="line">                <span class="meta">@Override</span></div><div class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">call</span><span class="params">(User note)</span> </span>&#123;</div><div class="line">                    search();</div><div class="line">                &#125;</div><div class="line">            &#125;);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><b>删</b></p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">delete</span><span class="params">()</span></span>&#123;</div><div class="line">	<span class="keyword">if</span>(mDatas.size()&lt;=<span class="number">0</span>)&#123;</div><div class="line">		<span class="keyword">return</span>;</div><div class="line">	&#125;</div><div class="line">	User user = mDatas.get(<span class="number">0</span>);</div><div class="line">	<span class="comment">//UserService.getInstance().delete(user);</span></div><div class="line">	<span class="comment">//UserService.getInstance().getDao().delete(user);</span></div><div class="line">	UserService.getInstance().getRxDao().delete(user)</div><div class="line">			.observeOn(AndroidSchedulers.mainThread())</div><div class="line">			.subscribe(<span class="keyword">new</span> Action1&lt;Void&gt;()&#123;</div><div class="line">				<span class="meta">@Override</span></div><div class="line">				<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">call</span><span class="params">(Void aVoid)</span></span>&#123;</div><div class="line">					search();</div><div class="line">				&#125;</div><div class="line">			&#125;);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><b>改</b></p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">update</span><span class="params">()</span></span>&#123;</div><div class="line">    String userName = user_name.getText().toString();</div><div class="line">    <span class="keyword">if</span>(TextUtils.isEmpty(userName))&#123;</div><div class="line">        <span class="keyword">return</span>;</div><div class="line">    &#125;</div><div class="line">    User user = mDatas.get(<span class="number">0</span>);</div><div class="line">    user.setName(userName);</div><div class="line">    <span class="comment">//UserService.getInstance().update(user);</span></div><div class="line">    <span class="comment">//UserService.getInstance().getDao().update(user);</span></div><div class="line">    UserService.getInstance().getRxDao().update(user)</div><div class="line">            .observeOn(AndroidSchedulers.mainThread())</div><div class="line">            .subscribe(<span class="keyword">new</span> Action1&lt;User&gt;()&#123;</div><div class="line">                <span class="meta">@Override</span></div><div class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">call</span><span class="params">(User user)</span></span>&#123;</div><div class="line">                    search();</div><div class="line">                &#125;</div><div class="line">            &#125;);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><b>查</b></p>
<p>ID降序查询所有数据</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">search</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="comment">//List&lt;User&gt; users = UserService.getInstance().getQueryBuilder().orderDesc(UserDao.Properties.Id).build().list();</span></div><div class="line">    UserService.getInstance().getQueryBuilder().orderDesc(UserDao.Properties.Id).rx().list()</div><div class="line">            .observeOn(AndroidSchedulers.mainThread())</div><div class="line">            .subscribe(<span class="keyword">new</span> Action1&lt;List&lt;User&gt;&gt;()&#123;</div><div class="line">                <span class="meta">@Override</span></div><div class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">call</span><span class="params">(List&lt;User&gt; users)</span></span>&#123;</div><div class="line">                    mDatas.clear();</div><div class="line">                    <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>;i&lt;users.size();i++)&#123;</div><div class="line">                        User user = users.get(i);</div><div class="line">                        mDatas.add(user);</div><div class="line">                    &#125;</div><div class="line">                    adapter.notifyDataSetChanged();</div><div class="line">                &#125;</div><div class="line">            &#125;);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>用Rx模式模糊查询</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">searchByName</span><span class="params">()</span> </span>&#123;</div><div class="line">    String userName = user_name.getText().toString();</div><div class="line">    <span class="keyword">if</span>(TextUtils.isEmpty(userName))&#123;</div><div class="line">        <span class="keyword">return</span>;</div><div class="line">    &#125;</div><div class="line">    <span class="comment">//方式一</span></div><div class="line">    <span class="comment">//List&lt;User&gt; users = UserService.getInstance().getDao().queryBuilder().where(UserDao.Properties.Name.like("%"+userName+"%")).build().list();</span></div><div class="line">    <span class="comment">//方式二</span></div><div class="line">    <span class="comment">//List&lt;User&gt; users = UserService.getInstance().getDao().queryBuilder().where(new WhereCondition.PropertyCondition(UserDao.Properties.Name, " LIKE ?", "%"+userName+"%")).build().list();</span></div><div class="line">    <span class="comment">//方式三</span></div><div class="line">    UserService.getInstance().getQueryBuilder().where(<span class="keyword">new</span> WhereCondition.PropertyCondition(UserDao.Properties.Name, <span class="string">" LIKE ?"</span>, <span class="string">"%"</span>+userName+<span class="string">"%"</span>)).rx().list()</div><div class="line">            .observeOn(AndroidSchedulers.mainThread())</div><div class="line">            .subscribe(<span class="keyword">new</span> Action1&lt;List&lt;User&gt;&gt;()&#123;</div><div class="line">                <span class="meta">@Override</span></div><div class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">call</span><span class="params">(List&lt;User&gt; users)</span></span>&#123;</div><div class="line">                    mDatas.clear();</div><div class="line">                    <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>;i&lt;users.size();i++)&#123;</div><div class="line">                        User user = users.get(i);</div><div class="line">                        mDatas.add(user);</div><div class="line">                    &#125;</div><div class="line">                    adapter.notifyDataSetChanged();</div><div class="line">                &#125;</div><div class="line">            &#125;);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="升级"><a href="#升级" class="headerlink" title="升级"></a>升级</h3><p><b>字段更新</b><br>这里借鉴了国外大牛写的一个工具类，代码如下：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MigrationHelper</span></span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String CONVERSION_CLASS_NOT_FOUND_EXCEPTION = <span class="string">"MIGRATION HELPER - CLASS DOESN'T MATCH WITH THE CURRENT PARAMETERS"</span>;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> MigrationHelper instance;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> MigrationHelper <span class="title">getInstance</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">if</span>(instance == <span class="keyword">null</span>) &#123;</div><div class="line">            instance = <span class="keyword">new</span> MigrationHelper();</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> instance;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">migrate</span><span class="params">(Database db, Class&lt;? extends AbstractDao&lt;?, ?&gt;&gt;... daoClasses)</span> </span>&#123;</div><div class="line">        generateTempTables(db, daoClasses);</div><div class="line">        DaoMaster.dropAllTables(db, <span class="keyword">true</span>);</div><div class="line">        DaoMaster.createAllTables(db, <span class="keyword">false</span>);</div><div class="line">        restoreData(db, daoClasses);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">generateTempTables</span><span class="params">(Database db, Class&lt;? extends AbstractDao&lt;?, ?&gt;&gt;... daoClasses)</span> </span>&#123;</div><div class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; daoClasses.length; i++) &#123;</div><div class="line">            DaoConfig daoConfig = <span class="keyword">new</span> DaoConfig(db, daoClasses[i]);</div><div class="line"></div><div class="line">            String divider = <span class="string">""</span>;</div><div class="line">            String tableName = daoConfig.tablename;</div><div class="line">            String tempTableName = daoConfig.tablename.concat(<span class="string">"_TEMP"</span>);</div><div class="line">            ArrayList&lt;String&gt; properties = <span class="keyword">new</span> ArrayList&lt;&gt;();</div><div class="line"></div><div class="line">            StringBuilder createTableStringBuilder = <span class="keyword">new</span> StringBuilder();</div><div class="line"></div><div class="line">            createTableStringBuilder.append(<span class="string">"CREATE TABLE "</span>).append(tempTableName).append(<span class="string">" ("</span>);</div><div class="line"></div><div class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; daoConfig.properties.length; j++) &#123;</div><div class="line">                String columnName = daoConfig.properties[j].columnName;</div><div class="line"></div><div class="line">                <span class="keyword">if</span>(getColumns(db, tableName).contains(columnName)) &#123;</div><div class="line">                    properties.add(columnName);</div><div class="line"></div><div class="line">                    String type = <span class="keyword">null</span>;</div><div class="line"></div><div class="line">                    <span class="keyword">try</span> &#123;</div><div class="line">                        type = getTypeByClass(daoConfig.properties[j].type);</div><div class="line">                    &#125; <span class="keyword">catch</span> (Exception exception) &#123;</div><div class="line">                        exception.printStackTrace();</div><div class="line">                        <span class="comment">//Crashlytics.logException(exception);</span></div><div class="line">                    &#125;</div><div class="line"></div><div class="line">                    createTableStringBuilder.append(divider).append(columnName).append(<span class="string">" "</span>).append(type);</div><div class="line"></div><div class="line">                    <span class="keyword">if</span>(daoConfig.properties[j].primaryKey) &#123;</div><div class="line">                        createTableStringBuilder.append(<span class="string">" PRIMARY KEY"</span>);</div><div class="line">                    &#125;</div><div class="line"></div><div class="line">                    divider = <span class="string">","</span>;</div><div class="line">                &#125;</div><div class="line">            &#125;</div><div class="line">            createTableStringBuilder.append(<span class="string">");"</span>);</div><div class="line"></div><div class="line">            db.execSQL(createTableStringBuilder.toString());</div><div class="line"></div><div class="line">            StringBuilder insertTableStringBuilder = <span class="keyword">new</span> StringBuilder();</div><div class="line"></div><div class="line">            insertTableStringBuilder.append(<span class="string">"INSERT INTO "</span>).append(tempTableName).append(<span class="string">" ("</span>);</div><div class="line">            insertTableStringBuilder.append(TextUtils.join(<span class="string">","</span>,properties));</div><div class="line">            insertTableStringBuilder.append(<span class="string">") SELECT "</span>);</div><div class="line">            insertTableStringBuilder.append(TextUtils.join(<span class="string">","</span>, properties));</div><div class="line">            insertTableStringBuilder.append(<span class="string">" FROM "</span>).append(tableName).append(<span class="string">";"</span>);</div><div class="line"></div><div class="line">            db.execSQL(insertTableStringBuilder.toString());</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">restoreData</span><span class="params">(Database db, Class&lt;? extends AbstractDao&lt;?, ?&gt;&gt;... daoClasses)</span> </span>&#123;</div><div class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; daoClasses.length; i++) &#123;</div><div class="line">            DaoConfig daoConfig = <span class="keyword">new</span> DaoConfig(db, daoClasses[i]);</div><div class="line"></div><div class="line">            String tableName = daoConfig.tablename;</div><div class="line">            String tempTableName = daoConfig.tablename.concat(<span class="string">"_TEMP"</span>);</div><div class="line">            ArrayList&lt;String&gt; properties = <span class="keyword">new</span> ArrayList&lt;&gt;();</div><div class="line"></div><div class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; daoConfig.properties.length; j++) &#123;</div><div class="line">                String columnName = daoConfig.properties[j].columnName;</div><div class="line"></div><div class="line">                <span class="keyword">if</span>(getColumns(db, tempTableName).contains(columnName)) &#123;</div><div class="line">                    properties.add(columnName);</div><div class="line">                &#125;</div><div class="line">            &#125;</div><div class="line"></div><div class="line">            StringBuilder insertTableStringBuilder = <span class="keyword">new</span> StringBuilder();</div><div class="line"></div><div class="line">            insertTableStringBuilder.append(<span class="string">"INSERT INTO "</span>).append(tableName).append(<span class="string">" ("</span>);</div><div class="line">            insertTableStringBuilder.append(TextUtils.join(<span class="string">","</span>, properties));</div><div class="line">            insertTableStringBuilder.append(<span class="string">") SELECT "</span>);</div><div class="line">            insertTableStringBuilder.append(TextUtils.join(<span class="string">","</span>, properties));</div><div class="line">            insertTableStringBuilder.append(<span class="string">" FROM "</span>).append(tempTableName).append(<span class="string">";"</span>);</div><div class="line"></div><div class="line">            StringBuilder dropTableStringBuilder = <span class="keyword">new</span> StringBuilder();</div><div class="line"></div><div class="line">            dropTableStringBuilder.append(<span class="string">"DROP TABLE "</span>).append(tempTableName);</div><div class="line"></div><div class="line">            db.execSQL(insertTableStringBuilder.toString());</div><div class="line">            db.execSQL(dropTableStringBuilder.toString());</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> String <span class="title">getTypeByClass</span><span class="params">(Class&lt;?&gt; type)</span> <span class="keyword">throws</span> Exception</span>&#123;</div><div class="line">        <span class="keyword">if</span>(type.equals(String.class)) &#123;</div><div class="line">            <span class="keyword">return</span> <span class="string">"TEXT"</span>;</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">if</span>(type.equals(Long.class) || type.equals(Integer.class) || type.equals(<span class="keyword">long</span>.class)) &#123;</div><div class="line">            <span class="keyword">return</span> <span class="string">"INTEGER"</span>;</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">if</span>(type.equals(Boolean.class)) &#123;</div><div class="line">            <span class="keyword">return</span> <span class="string">"BOOLEAN"</span>;</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        Exception exception = <span class="keyword">new</span> Exception(CONVERSION_CLASS_NOT_FOUND_EXCEPTION.concat(<span class="string">" - Class: "</span>).concat(type.toString()));</div><div class="line">        <span class="comment">//Crashlytics.logException(exception);</span></div><div class="line">        <span class="keyword">throw</span> exception;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> List&lt;String&gt; <span class="title">getColumns</span><span class="params">(Database db,String tableName)</span> </span>&#123;</div><div class="line">        List&lt;String&gt; columns = <span class="keyword">new</span> ArrayList&lt;&gt;();</div><div class="line">        Cursor cursor = <span class="keyword">null</span>;</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            cursor = db.rawQuery(<span class="string">"SELECT * FROM "</span> + tableName + <span class="string">" limit 1"</span>, <span class="keyword">null</span>);</div><div class="line">            <span class="keyword">if</span> (cursor != <span class="keyword">null</span>) &#123;</div><div class="line">                columns = <span class="keyword">new</span> ArrayList&lt;&gt;(Arrays.asList(cursor.getColumnNames()));</div><div class="line">            &#125;</div><div class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</div><div class="line">            Log.v(tableName,e.getMessage(),e);</div><div class="line">            e.printStackTrace();</div><div class="line">        &#125; <span class="keyword">finally</span> &#123;</div><div class="line">            <span class="keyword">if</span> (cursor != <span class="keyword">null</span>)</div><div class="line">                cursor.close();</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> columns;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>具体应用只需要在<code>OnlineOpenHelper</code>的<code>onUpgrade</code>方法中如下使用</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">switch</span>(oldVersion)&#123;</div><div class="line">    <span class="comment">//User表添加字段或删除字段更新</span></div><div class="line">    <span class="keyword">case</span> <span class="number">1</span>: MigrationHelper.getInstance().migrate(db,UserDao.class);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><b>新增数据表</b></p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="meta">@Entity</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Role</span></span>&#123;</div><div class="line"></div><div class="line">    <span class="meta">@Id</span></div><div class="line">    <span class="keyword">private</span> Long id;</div><div class="line">    </div><div class="line">    <span class="meta">@NotNull</span></div><div class="line">    <span class="keyword">private</span> String roleName;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>在OnlineOpenHelper的onUpgrade方法添加<code>RoleDao.createTable(db,false)</code>,如下：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">switch</span>(oldVersion)&#123;</div><div class="line">    <span class="comment">//User表添加字段或删除字段更新</span></div><div class="line">    <span class="keyword">case</span> <span class="number">1</span>: MigrationHelper.getInstance().migrate(db,UserDao.class);</div><div class="line">    <span class="comment">//第二个参数true or false 是否需要检查是否存在该表</span></div><div class="line">    <span class="keyword">case</span> <span class="number">2</span>: RoleDao.createTable(db,<span class="keyword">false</span>);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>到这里greenDao简单的操作处理都基本OK了！</p>
<p><a href="https://github.com/h7870181/CommonFrame/tree/master/greendaolibrary" target="_blank" rel="external">github地址</a></p>
<blockquote>
<p>写在最后的话：很多事情都从小事做起，坚持不懈，你一定能够把它做好</p>
</blockquote>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag"># Android</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/09/23/2016-09-23-rxjava/" rel="next" title="带大家进入RxJava的世界">
                <i class="fa fa-chevron-left"></i> 带大家进入RxJava的世界
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/10/Hexo学习和使用/" rel="prev" title="Hexo学习和使用">
                Hexo学习和使用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="Soaic" />
          <p class="site-author-name" itemprop="name">Soaic</p>
           
              <p class="site-description motion-element" itemprop="description">Welcome!</p>
           
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">1</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#特点"><span class="nav-number">2.</span> <span class="nav-text">特点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#资料"><span class="nav-number">3.</span> <span class="nav-text">资料</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#配置环境"><span class="nav-number">4.</span> <span class="nav-text">配置环境</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#开始"><span class="nav-number">5.</span> <span class="nav-text">开始</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#封装"><span class="nav-number">6.</span> <span class="nav-text">封装</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用"><span class="nav-number">7.</span> <span class="nav-text">使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#升级"><span class="nav-number">8.</span> <span class="nav-text">升级</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Soaic</span>
</div>

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("nSNhFcJCeysT9vRXgfNvtbQF-gzGzoHsz", "aegQNi8pntiOE4R2z0e5B84D");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>
